package com.lehecai.core.servlet;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 基础Servlet
 * 封装统一的获取Spring上下文方法
 * 封装统一的输出方法
 * @author Sunshow
 * 
 */
public abstract class CoreSpringBaseServlet extends CoreBaseServlet {

	private static final long serialVersionUID = 6546282975419782014L;

	// 定义Spring上下文环境
	private static ApplicationContext ctx = null;
	
	private static Lock lock = new ReentrantLock();

	private ApplicationContext getApplicationContext() {
		if (ctx != null) {
			return ctx;
		}

        lock.lock();
        if (ctx != null) {
            lock.unlock();
            return ctx;
        }

		ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        lock.unlock();
		return ctx;
	}

	// 获取Spring上下文环境
	protected Object getBean(String name) {
		ApplicationContext context = this.getApplicationContext();
		if (context == null) {
			logger.error("未获取到Spring上下文环境");
			return null;
		}
		return context.getBean(name);
	}

	protected <T> T getBean(String name, Class<T> clazz) {
		ApplicationContext context = this.getApplicationContext();
		if (context == null) {
			logger.error("未获取到Spring上下文环境");
			return null;
		}
		return context.getBean(name, clazz);
	}
}

